package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.Room;
import com.ruoyi.system.domain.RoomOrder;
import com.ruoyi.system.domain.RoomStatus;
import com.ruoyi.system.enums.RoomStatusEnum;
import com.ruoyi.system.service.IRoomOrderService;
import com.ruoyi.system.service.IRoomService;
import com.ruoyi.system.service.IRoomStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客房信息Controller
 *
 * @author 强盛酒店
 * @date 2023-03-07
 */
@RestController
@RequestMapping("/system/room")
public class RoomController extends BaseController {
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IRoomOrderService roomOrderService;
    @Autowired
    private IRoomStatusService roomStatusService;
    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 查询客房信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Room room) throws Exception {
        startPage();
        List<Room> list = roomService.selectRoomList(room);
        for (Room item : list) {
            RoomStatus roomStatus = new RoomStatus();
            if (room.getQueryTime()==null){
                roomStatus.setOrderDate(dateFormat.format(new Date()));
            }else {
                roomStatus.setOrderDate(dateFormat.format(room.getQueryTime()));
            }
            roomStatus.setRoomId(item.getId());
            List<RoomStatus> roomStatuses = roomStatusService.selectRoomStatusList(roomStatus);
            if (CollectionUtils.isEmpty(roomStatuses)){
                item.setStatusName(RoomStatusEnum.FREE.getName());
            }else {
                item.setStatusName(RoomStatusEnum.getEnum(roomStatuses.get(0).getStatus()).getName());
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询空闲客房信息列表
     */
    @GetMapping("/all")
    public AjaxResult all(@RequestParam("liveTime")String liveTime,@RequestParam("leaveTime")String leaveTime,
                          @RequestParam(value = "orderId",required = false)Long orderId,
                          @RequestParam(value = "type",required = false)Integer type) throws ParseException {
        Room resp = new Room();
        if (type!=null){
            resp.setType(type);
        }
        List<Room> list = roomService.selectRoomList(resp);
        List<Room> roomList = new ArrayList<>();
        List<String> everyDay = findEveryDay(liveTime, leaveTime);
        for (Room room : list) {
            List<RoomStatus> roomStatusList = new ArrayList<>();
            for (String day : everyDay) {
                List<RoomStatus> statusList = roomStatusService.selectRoomStatusList(new RoomStatus() {{
                    setRoomId(room.getId());
                    setOrderDate(dateFormat.format(new Date()));
                    setOrderDate(day);
                }});
                List<RoomStatus> collect = statusList.stream().filter(item -> !item.getStatus().equals(RoomStatusEnum.FREE.getCode())).collect(Collectors.toList());
                roomStatusList.addAll(collect);
            }
            if (CollectionUtils.isEmpty(roomStatusList)){
                roomList.add(room);
            }
        }
        if (orderId!=null){
            RoomOrder roomOrder = roomOrderService.selectRoomOrderById(orderId);
            Date live = dateFormat.parse(liveTime);
            Date leave = dateFormat.parse(leaveTime);
            if (roomOrder.getLiveTime().compareTo(live)<=0&&roomOrder.getLeaveTime().compareTo(leave)>=0){
                roomList.add(roomService.selectRoomById(roomOrder.getRoomId()));
            }
        }
        return success(roomList);
    }

    /**
     * 传入两个时间范围，返回这两个时间范围内的所有日期，并保存在一个集合中
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findEveryDay(String beginTime, String endTime)
            throws ParseException {
        //1.创建一个放所有日期的集合
        List<String> dates = new ArrayList<>();
        //2.创建时间解析对象规定解析格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //3.将传入的时间解析成Date类型,相当于格式化
        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        //4.将格式化后的第一天添加进集合
        dates.add(sdf.format(dBegin));
        //5.使用本地的时区和区域获取日历
        Calendar calBegin = Calendar.getInstance();
        //6.传入起始时间将此日历设置为起始日历
        calBegin.setTime(dBegin);
        //8.判断结束日期是否在起始日历的日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 9.根据日历的规则:月份中的每一天，为起始日历加一天
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            //10.得到的每一天就添加进集合
            dates.add(sdf.format(calBegin.getTime()));
            //11.如果当前的起始日历超过结束日期后,就结束循环
        }
        return dates;
    }

    /**
     * 获取客房信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(roomService.selectRoomById(id));
    }

    /**
     * 新增客房信息
     */
    @PostMapping
    public AjaxResult add(@RequestBody Room room) throws Exception {
        return toAjax(roomService.insertRoom(room));
    }

    /**
     * 修改客房信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Room room) throws Exception {
        return toAjax(roomService.updateRoom(room));
    }

    /**
     * 删除客房信息
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(roomService.deleteRoomByIds2(ids));
    }
}
